import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';

function useRequest(url) {

    /* 定义一堆响应式数据 */
    const data = ref(null);
    const loading = ref(false);
    const error = ref(null);

    let source = null;

    async function fetchData() {
        loading.value = true;
        error.value = null;
        data.value = null

        try {
            // 创建一个请求取消令牌
            source = axios.CancelToken.source();

            const response = await axios.get(url, { cancelToken: source.token });
            // data.value = response.data

            data.value = await new Promise(
                resolve => {
                    setTimeout(() => {
                        resolve(response.data)
                    }, 3000);
                }
            )

        }

        catch (e) {
            if (axios.isCancel(e)) {
                console.log('请求已取消');
                error.value = '请求已取消'
            } else {
                error.value = e;
            }
        }

        finally {
            loading.value = false;
        }
    }

    // 在组件挂载时发起请求
    onMounted(() => {
        fetchData();
    });

    // 在组件卸载时取消请求
    onUnmounted(() => {
        if (source) {
            source.cancel('组件卸载，请求被取消');
        }
    });

    return {
        data,
        loading,
        error,
        fetchData,
    };
    
}

export default useRequest;